/*
 * @Author: HuRrongChao 1556810922@qq.com
 * @Date: 2024-04-29 18:32:23
 * @LastEditors: HuRrongChao
 * @LastEditTime: 2025-02-08 17:02:39
 */
// 生成缩略图

const fs = require('fs');
const path = require('path');
const puppeteer = require('puppeteer-core');

// 源视频目录和目标缩略图目录
const videoDir = path.join(process.cwd(), 'public', 'upload', 'video_list');
const thumbnailDir = path.join(process.cwd(), 'public', 'upload', 'thumb_list');

// 确保缩略图目录存在
if (!fs.existsSync(thumbnailDir)) {
    fs.mkdirSync(thumbnailDir, { recursive: true });
}

async function extractThumbnails() {
    const browser = await puppeteer.launch({
        executablePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', // Windows路径示例
        // executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', // macOS路径示例
        // executablePath: '/usr/bin/google-chrome', // Linux路径示例
    });
    const page = await browser.newPage();
    
    try {
        // 注入处理视频的HTML和JavaScript
        await page.setContent(`
            <html>
                <body>
                    <video id="video" style="display: none;"></video>
                    <canvas id="canvas" style="display: none;"></canvas>
                </body>
            </html>
        `);

        // 读取视频目录中的所有文件
        const files = fs.readdirSync(videoDir);
        const videoFiles = files.filter(file => 
            ['.mp4', '.avi', '.mov', '.wmv'].includes(path.extname(file).toLowerCase())
        );

        // 处理每个视频文件
        for (const videoFile of videoFiles) {
            const videoPath = path.join(videoDir, videoFile);
            const thumbnailPath = path.join(
                thumbnailDir,
                `${path.parse(videoFile).name}.jpg`
            );

            // 将视频文件转换为base64
            const videoBuffer = fs.readFileSync(videoPath);
            const videoBase64 = videoBuffer.toString('base64');
            const videoSrc = `data:video/${path.extname(videoFile).slice(1)};base64,${videoBase64}`;

            // 在浏览器中捕获视频首帧
            const base64Image = await page.evaluate(async (src) => {
                return new Promise((resolve, reject) => {
                    const video = document.getElementById('video');
                    const canvas = document.getElementById('canvas');
                    const ctx = canvas.getContext('2d');

                    // 添加更多的事件监听来确保视频已经准备好
                    video.addEventListener('loadedmetadata', () => {
                        video.currentTime = 0; // 确保我们在第一帧
                    });

                    video.addEventListener('seeked', () => {
                        // 视频已经跳转到指定时间点
                        canvas.width = video.videoWidth;
                        canvas.height = video.videoHeight;
                        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                        const base64Data = canvas.toDataURL('image/jpeg');
                        resolve(base64Data);
                    });

                    video.onerror = reject;
                    video.src = src;
                });
            }, videoSrc);

            // 将base64图像数据保存为文件
            const base64Data = base64Image.replace(/^data:image\/jpeg;base64,/, '');
            fs.writeFileSync(thumbnailPath, base64Data, 'base64');
            
            console.log(`已生成缩略图: ${thumbnailPath}`);
        }

        console.log('所有缩略图提取完成！');
    } catch (error) {
        console.error('处理过程中出错:', error);
    } finally {
        await browser.close();
    }
}

// 运行程序
extractThumbnails();
